package com.bjc.wxpay.controller;

import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.bjc.base.bean.request.BorrowReturnLogReqVO;
import com.bjc.base.bean.request.UserReqVO;
import com.bjc.base.bean.response.BorrowReturnLogVO;
import com.bjc.base.bean.response.UserVO;
import com.bjc.base.service.IBorrowReturnLogService;
import com.bjc.base.service.IUserService;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.WxMpMassOpenIdsMessage;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.result.WxMpMassSendResult;

/**
 * 
 * @author xuzihui
 *
 */
@Component
@Slf4j
public class AsyncTask {

	@Autowired
	private IBorrowReturnLogService borrowReturnLogService;
	@Autowired
	private IUserService userService;
	@Autowired
	private WxMpService wxMpService;

	private static String returnMessage = "绘本借阅到期⏰\r\n\r\n亲爱的小鱼儿粉:\r\n"
			+ "        您家小朋友借阅的绘本《{0}》已于{1}到期，请尽快归还绘本至附近借阅点并在系统中归还或在系统中直接续借！(如已归还到实体借阅点，请在系统中点击归还。)\r\n"
			+ "         引导小朋友从小培养时间管理能力, 长大更有出息！\r\n" + "         如有任何问题，请不吝联系小鱼儿客服（微信号bj18010039827）！\r\n"
			+ "        祝小朋友健康快乐地成长～ [Heart]";

	/**
	 * 每天中午12点执行 发送逾期提醒
	 * 
	 * @throws WxErrorException
	 */
	@Async
	//@PostConstruct // 测试
	@Scheduled(cron = "0 30 16 * * ?") // 每天16:30点执行
	// @Scheduled(cron = "30 * * * * ?") //测试，每30秒
	public void sendReturnMessage() throws WxErrorException {
		log.info("====================定时归还提醒开始=================" + wxMpService);
		BorrowReturnLogReqVO record = new BorrowReturnLogReqVO();
		record.setRorrowFlag(1);
		List<BorrowReturnLogVO> borrowReturnLogVOs = borrowReturnLogService.getList(record);

		int size = borrowReturnLogVOs.size();
		log.info("通知条数" + size);
		for (BorrowReturnLogVO borrowReturnLogVO : borrowReturnLogVOs) {
			Integer uid = borrowReturnLogVO.getUid();
			UserReqVO userReqVO = new UserReqVO();
			userReqVO.setId(uid);

			// 许自辉测试
			// userReqVO.setId(1017);
			UserVO user = userService.get(userReqVO);
			String openId = user.getOpenid();
			LocalDateTime startTime = borrowReturnLogVO.getBorrowStartTime();
			Integer weeks = borrowReturnLogVO.getBorrowWeeks();
			String bookName = borrowReturnLogVO.getBook().getBookName();
			LocalDateTime endTime = startTime.plusWeeks(Long.parseLong(weeks.toString()));
			// String message =
			// "你的绘本借阅在"+endTime+"已到期，请您入如期归还，或点击续借。三天内免费归还，超过三天需支付一周的逾期费用！";
			String message = MessageFormat.format(returnMessage, bookName, endTime).replace("T", " ");
			// 发送客服消息
			sendMessage(openId, message);

			// 群发消息（客服消息好像没用）
			// WxMpMassOpenIdsMessage massMessage = new WxMpMassOpenIdsMessage();
			// massMessage.setMsgType(WxConsts.MassMsgType.TEXT);
			// massMessage.setContent(message);
			// massMessage.getToUsers().add(openId);
			// //WxMpMassSendResult massResult =
			// wxMpService.getMassMessageService().massOpenIdsMessageSend(massMessage);
		}

		log.info("====================定时归还提醒结束=================");

		// 发送客服消息
		WxMpKefuMessage kefuMessage = WxMpKefuMessage.TEXT().toUser("opjOAv6FzHn8yyWtlXyw0P9NGW9A")
				.content(LocalDateTime.now() + "催还提醒条数：" + size).build();
		wxMpService.getKefuService().sendKefuMessage(kefuMessage);
	}

	@Async
	private void sendMessage(String openId, String message) {
		WxMpKefuMessage kefuMessage = WxMpKefuMessage.TEXT().toUser(openId).content(message).build();
		try {
			wxMpService.getKefuService().sendKefuMessage(kefuMessage);
		} catch (WxErrorException e) {
			log.error(openId + "异常" + e.getMessage());
		}
	}

}
